#include "Game.h"

using namespace std;

Game::Game()
{
	//ctor
	m_isEixt = false;
	//m_Player_lst.clear();
}

Game::~Game()
{
	//dtor
	//m_Player_lst.clear();
}

// YU_TODO:
void CallTcpServerLoop(TcpServer* _pSock)
{
	_pSock->ConnectLoop();
}


void CallTcpClientLoop(TcpClient* _pSock)
{
	_pSock->RecvSendLoop();
}


void Game::Init()
{
	/// 配置读取
	Config::LoadGlobalConfig("GameGlobalConfig.txt");

	/// 网络启动
	// 服务器部分Test
    string gameIp = Config::globalConfig_map["GameServerIp"];
    uint16_t gamePort = std::atoi( Config::globalConfig_map["GameServerPort"].c_str() );
    if(0 == m_ServerSock.Init(gameIp, gamePort))
	{
		std::thread thread1(CallTcpServerLoop, &m_ServerSock);
		thread1.detach();
	}

	// 客户端部分Test
    string worldIp = Config::globalConfig_map["WorldServerIp"];
    uint16_t worldPort = std::atoi( (Config::globalConfig_map["WorldServerPort"]).c_str() );
	m_ClientSock.Init(worldIp, worldPort);
	if(0 == m_ClientSock.Connect())
	{
		 std::thread thread2(CallTcpClientLoop, &m_ClientSock);
		 thread2.detach();
	}

	//
	m_Login.Init();


}


void Game::Dispose()
{

}

TcpServer* Game::GetSock()
{
	return &m_ServerSock;
}

void Game::GameLoop(){
	Debug::State("Start ", __func__);
	while(!m_isEixt){

		// 处理ServerSock 发送消息
		if(!m_ServerSock.GetMsgQunue().IsSendEmpty()){
			Message Msg = m_ServerSock.GetMsgQunue().m_MsgSend_que.front();
			m_ServerSock.Send(&Msg);
			m_ServerSock.GetMsgQunue().m_MsgSend_que.pop();
		}

		// 处理ServerSock 接受消息
		if (!m_ServerSock.GetMsgQunue().IsRecvEmpty()){
			Message Msg = m_ServerSock.GetMsgQunue().m_MsgRecv_que.front();
			m_MsgRounter.ServerRounter(&Msg);
			m_ServerSock.GetMsgQunue().m_MsgRecv_que.pop();
		}

		// 处理ClientSock 发送消息
		if(!m_ClientSock.GetMsgQunue().IsSendEmpty()){
			Message Msg = m_ClientSock.GetMsgQunue().m_MsgSend_que.front();
			m_ClientSock.Send(&Msg);
			m_ClientSock.GetMsgQunue().m_MsgSend_que.pop();
		}

		// 处理ClientSock 接受消息
		if(!m_ClientSock.GetMsgQunue().IsRecvEmpty()){
			Message Msg = m_ClientSock.GetMsgQunue().m_MsgRecv_que.front();
			m_MsgRounter.ClientRounter(&Msg);
			m_ClientSock.GetMsgQunue().m_MsgRecv_que.pop();
		}
	}
}

// exit
void Game::Exit(){
	m_isEixt = true;
}

Login* Game::GetLogin()
{
	return &m_Login;
}

TcpClient* Game::GetSockClient()
{
	return &m_ClientSock;
}

PlayerManager* Game::GetPlayerMgr()
{
	return &m_PlayerMgr;
}

RoleManager* Game::GetRoleMgr()
{
	return &m_RoleMgr;
}

